package tzhomestudio.framework.shared.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnzipUtils {
    // Main data
	private String inputZipFile;
	private String outputFolder;

    private String rootFolder;

	public UnzipUtils(String inputZipFile, String outputFolder) {
		this.inputZipFile = inputZipFile;
		this.outputFolder = outputFolder;
	}

    public String getRootFolder() {
        return rootFolder;
    }
	
	public void run() throws IOException {
		unZipIt(inputZipFile, outputFolder);
	}
	
	public void unZipIt(String zipFile, String outputFolder) throws IOException {
		byte[] buffer = new byte[1024];

        // create output directory is not exists
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }

        // get the zip file content
        ZipInputStream zis = new ZipInputStream(
                new FileInputStream(zipFile));
        // get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator
                    + fileName);

            if (rootFolder == null)
                rootFolder = newFile.getAbsoluteFile().toString();

            System.out.println("file unzip : " + newFile.getAbsoluteFile());

            // create all non exists folders
            // else you will hit FileNotFoundException for compressed folder

            if (ze.isDirectory()) {
                new File(newFile.getParent()).mkdirs();
            } else {
                FileOutputStream fos = null;

                new File(newFile.getParent()).mkdirs();

                fos = new FileOutputStream(newFile);

                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

                fos.close();
            }

            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();
	}
}
